import { Reducer } from 'redux';
import { Effect } from 'dva';
import { PersonalRadioItem } from '@/domains/radio';
import { getAfternoonList, getEveningList, getMorningList } from './service';

const host = 'http://cdn2.xinletuedu.cn';

export interface StateType {
  radioList: PersonalRadioItem[];
  selected: PersonalRadioItem | null;
  tabKey: string;
}

export interface ModelType {
  namespace: string;
  state: StateType;
  effects: {
    fetchRadioList: Effect;
  };
  reducers: {
    saveData: Reducer;
    changeSelected: Reducer;
  };
}

const model: ModelType = {
  namespace: 'personalRadio',

  state: {
    radioList: [],
    selected: null,
    tabKey: 'morning',
  },

  effects: {
    *fetchRadioList({ payload, callback }, { call, put }) {
      const rows = yield call(
        payload === 'morning'
          ? getMorningList
          : payload === 'afternoon'
          ? getAfternoonList
          : getEveningList,
      );
      const radioList: PersonalRadioItem[] = [];
      rows.forEach((item: PersonalRadioItem) => {
        radioList.push({
          ...item,
          audio: host + item.audio,
          banner: host + item.banner,
          description: (item.audio || '').split('/')[3],
        });
        if (item.audioIi) {
          radioList.push({
            ...item,
            id: item.id + Math.round(Math.random() * 100000),
            title: item.titleIi,
            audio: host + item.audioIi,
            banner: host + item.banner,
            description: (item.audioIi || '').split('/')[3],
          });
        }
      });
      yield put({
        type: 'saveData',
        payload: { radioList, selected: radioList[0], tabKey: payload },
      });
      if (callback) callback();
    },
  },

  reducers: {
    saveData(state, { payload }) {
      return { ...state, ...payload };
    },
    changeSelected(state, { payload }) {
      const { selected, radioList } = state;
      if (radioList.length) {
        if (selected) {
          const index = radioList.findIndex((item: PersonalRadioItem) => item.id === selected.id);
          if (payload === 'next') {
            if (index === radioList.length - 1) {
              return { ...state, selected: radioList[0] };
            }
            return { ...state, selected: radioList[index + 1] };
          }
          if (index === 0) {
            return { ...state, selected: radioList[radioList.length - 1] };
          }
          return { ...state, selected: radioList[index - 1] };
        }
        return { ...state, selected: radioList[0] };
      }
      return state;
    },
  },
};

export default model;
